package com.token.iot.bratterycharging.gateway.oper;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.gson.Gson;
import com.outstanding.framework.base.mq.MQProducer;
import com.outstanding.framework.core.PendingException;
import com.token.iot.bratterycharging.gateway.AbstractOper;
import com.token.iot.bratterycharging.gateway.ChannelHandlerContextManager;
import com.token.iot.bratterycharging.gateway.IDGeneration;
import com.token.iot.bratterycharging.gateway.Oper;
import com.token.iot.bratterycharging.gateway.api.Constant;
import com.token.iot.bratterycharging.gateway.api.Device;
import com.token.iot.bratterycharging.gateway.dao.DeviceDAO;
import com.token.iot.bratterycharging.gateway.utils.ChannelHandlerContextUtil;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;

/**
 * 获取返回的IMEI值,会去查询一下是否在设备登记表中，如果没有，则增加一笔
 * 
 * @author chenzhixuan
 *
 */
@Component("ADVOper")
public class ADVOper extends AbstractOper {


	
	@Autowired
	private MQProducer mQProducer;
	
	@Autowired
	private DeviceDAO dao;

	
	private static ChannelHandlerContextManager manager = new ChannelHandlerContextManager();

	static public final AttributeKey<String> attributeKey = AttributeKey.valueOf("IMEI");

	@Override
	public int onCall(byte[] b, ChannelHandlerContext ctx) throws PendingException {
		String val = new String(b);
		String imei = val.substring(18);
		String sessionid = IDGeneration.getSessionID(b);
		manager.putIfAbsent(imei, ctx);
		Attribute<String> attr = ctx.channel().attr(attributeKey);
		attr.set(imei);
		//登记设备
		Device d = new Device();
		d.setImei(imei);
		String ip = ChannelHandlerContextUtil.getIP(ctx);
		d.setIp(ip);
		//查找设备
		Device r = dao.selectByImei(d.getImei());
		Gson gs = new Gson();
		String str = null;
		//设备不存在
		if(r == null) {
			dao.insert(d);
			str = gs.toJson(d);
		}else {
			dao.update(r.getIp(),r.getId());
			str = gs.toJson(r);
		}
		//发送的字符json
		mQProducer.sendMessageByTopic(Constant.MESSAGEHEAD+Constant.QueueDeviceON, str);
		
		return 0;
	}

}
